from itertools import groupby

from odoo import api,fields, models
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.exceptions import UserError


class StockQuantReport(models.Model):
    _name = 'stock.quant.report'
    _description = "Stock Quant Report"
    _auto = False

    stock_quant_id = fields.Many2one('stock.quant')
    location_id = fields.Many2one('stock.location', string='Location Name')
    product_id = fields.Many2one('product.product', 'Product')
    description_eng = fields.Text(related='product_id.description_eng', string='Description Engnish')
    product_code = fields.Char(related='product_id.default_code',string='Product Code')
    initial_qty = fields.Float(string="Initial Qty", compute="_compute_initial_qty", compute_sudo=True)
    lot_id = fields.Many2one('stock.lot', 'Lot')
    quantity = fields.Float('Quantity')
    product_uom_id = fields.Many2one('uom.uom', related='product_id.uom_id',string='Unit of Measure')


    @api.depends('lot_id')
    def _compute_initial_qty(self):
        for rec in self:
            move_lines = rec.stock_quant_id.get_inventory_history()
            if move_lines:
                # 按照 decoration-success 判断入库记录
                incoming_move_lines = move_lines.filtered(
                    lambda line: (line.location_usage not in ('internal', 'transit')) and
                                 (line.location_dest_usage in ('internal', 'transit'))
                )
                # 如果有入库记录
                if incoming_move_lines:
                    # 按日期排序取最早的入库记录
                    # earliest_move = incoming_move_lines.sorted(key=lambda line: line.date)
                    # earliest_move = earliest_move[0]  # 获取最早的入库记录
                    rec.initial_qty = sum(incoming_move_lines.mapped('quantity'))
                else:
                    rec.initial_qty = 0
            else:
                rec.initial_qty = 0


    @property
    def _table_query(self):

        return  f"""
        SELECT ROW_NUMBER
	( ) OVER ( ) AS ID,
	sq.id as stock_quant_id,
	sq.location_id,
	sq.product_id,
	sq.lot_id,
	sq.quantity 
FROM
	stock_quant sq left join stock_location sl on sq.location_id=sl.id
	where sl.usage='internal' and sq.quantity>0

        """
